package chapter07

object Demo01_ImmutableArray {
  def main(args: Array[String]): Unit = {
    //创建不可变数组
    val arr: Array[Int] = new Array[Int](5)

    val arr2 = Array(1,2,3,4,5)

    //访问元素
    println(arr(0))
    println(arr(1))

    //修改元素
    arr(0) = 1
    arr(2) = 3
    println(arr(0))
    println(arr(2))

    //循环做数组遍历
    //1)
    for (i <- 0 until  arr.length ) print(arr(i))
    println()
    println("=========================")
    for (i <- arr.indices) print(arr2(i))
    println()
    println("=========================")
    //2)增强for循环
    //直接遍历所有元素
    for (elem <- arr2) print(elem)
    println()
    println("=========================")

    //3) 迭代器
    val iter = arr2.iterator
    while (iter.hasNext) {
      print(iter.next())
      println()
    }
    println("=========================")

    //4）调用foreach循环
    arr2.foreach((elem: Int) => println(elem))
    println()
    println("=========================")

    arr.foreach(println)

    println(arr2.mkString("--"))

    //添加元素
    //  :+   表示要把添加的元素添加到末尾  +: 表示添加到开头
    val newArr = arr2.:+(88)
    println(newArr.mkString("-"))

    val newArr1 = arr2.+:(77)
    println(newArr1.mkString("-"))

    val newArr2 = arr2 :+ 45
    println(newArr2.mkString("+"))

    val newArr3 = 888 +: 999 +: 777 +:arr2 :+666 :+555
    println(newArr3.mkString(" "))
  }
}
